// pages/transactions/transactions.js
const app = getApp();

Page({
  data: {
    roomId: '',
    transactions: [],
    groupedTransactions: [],
    activeFilter: 'all', // all, income, expense
    sortOrder: 'desc', // asc, desc
    page: 1,
    pageSize: 20,
    hasMore: true,
    loading: false,
    
    // 统计数据
    totalTransactions: 0,
    totalIncome: 0,
    myTransactions: 0,
    
    // 充值/转账相关
    transactionType: '', // recharge, transfer, record
    rechargeAmounts: [100, 200, 500, 1000, 2000],
    selectedAmount: 0,
    customAmount: '',
    transferTo: '',
    transferAmount: '',
    transferRemark: ''
  },
  
  onLoad: function(options) {
    // 确定页面类型：充值、转账或交易记录
    if (options.type === 'recharge') {
      this.setData({ transactionType: 'recharge' });
      wx.setNavigationBarTitle({ title: '账户充值' });
    } else if (options.type === 'transfer') {
      this.setData({ transactionType: 'transfer' });
      wx.setNavigationBarTitle({ title: '转账' });
    } else {
      this.setData({ 
        transactionType: 'record',
        roomId: options.room_id || ''
      });
      // 加载交易记录
      this.loadTransactions();
    }
  },
  
  // 加载交易记录
  loadTransactions: function(append = false) {
    if (this.data.loading || (!append && !this.data.hasMore)) {
      return;
    }
    
    this.setData({ loading: true });
    
    // 由于是模拟环境，使用模拟数据
    setTimeout(() => {
      const mockTransactions = [
        {
          id: '1',
          user_name: '张三',
          avatar: '/assets/icons/default-avatar.png',
          description: '斗地主',
          amount: 150,
          time: '19:30',
          date: '2024-01-20',
          created_at: new Date().toISOString()
        },
        {
          id: '2',
          user_name: '李四',
          avatar: '/assets/icons/default-avatar.png',
          description: '麻将',
          amount: -80,
          time: '16:45',
          date: '2024-01-20',
          created_at: new Date().toISOString()
        },
        {
          id: '3',
          user_name: '系统',
          avatar: '',
          description: '充值',
          amount: 500,
          time: '18:00',
          date: '2024-01-20',
          created_at: new Date().toISOString()
        }
      ];
      
      this.setData({
        transactions: mockTransactions,
        hasMore: false,
        loading: false
      });
      
      // 应用筛选并分组
      this.applyFilter();
      
      // 更新统计数据
      this.updateStatistics();
      
    }, 500);
    
    /* 实际API调用代码
    const that = this;
    
    app.request(`/transaction/room/${this.data.roomId}`, {
      params: {
        page: this.data.page,
        page_size: this.data.pageSize,
        sort_order: this.data.sortOrder
      }
    }).then(res => {
      wx.hideLoading();
      
      const formattedTransactions = res.map(t => ({
        id: t.id,
        user_name: t.other_user_name,
        avatar: t.other_user_avatar || '',
        description: t.description || `与${t.other_user_name}的交易`,
        amount: t.amount,
        time: that.formatTime(t.created_at),
        date: that.formatDate(t.created_at),
        created_at: t.created_at
      }));
      
      let newTransactions = append ? 
        [...this.data.transactions, ...formattedTransactions] : 
        formattedTransactions;
      
      this.setData({
        transactions: newTransactions,
        page: append ? this.data.page + 1 : 2,
        hasMore: formattedTransactions.length === this.data.pageSize,
        loading: false
      });
      
      // 应用筛选并分组
      this.applyFilter();
      
      // 更新统计数据
      this.updateStatistics();
    }).catch(() => {
      this.setData({ loading: false });
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      });
    });
    */
  },
  
  // 应用筛选
  applyFilter: function() {
    let filteredTransactions = [...this.data.transactions];
    
    // 应用筛选条件
    if (this.data.activeFilter === 'income') {
      filteredTransactions = filteredTransactions.filter(t => t.amount > 0);
    } else if (this.data.activeFilter === 'expense') {
      filteredTransactions = filteredTransactions.filter(t => t.amount < 0);
    }
    
    // 按日期分组
    const grouped = {};
    filteredTransactions.forEach(transaction => {
      if (!grouped[transaction.date]) {
        grouped[transaction.date] = {
          date: transaction.date,
          summary: 0,
          transactions: []
        };
      }
      
      grouped[transaction.date].transactions.push(transaction);
      grouped[transaction.date].summary += transaction.amount;
    });
    
    // 转换为数组并按日期排序
    const groupedArray = Object.values(grouped).sort((a, b) => {
      // 按日期排序，最新的在前
      const dateA = new Date(a.date);
      const dateB = new Date(b.date);
      return this.data.sortOrder === 'desc' ? 
        dateB - dateA : 
        dateA - dateB;
    });
    
    this.setData({ groupedTransactions: groupedArray });
  },
  
  // 更新统计数据
  updateStatistics: function() {
    const userId = app.globalData.userInfo.id;
    
    // 统计所有交易中的净收益
    let totalIncome = 0;
    let myTransactions = 0;
    
    this.data.transactions.forEach(transaction => {
      totalIncome += transaction.amount;
      if (transaction.from_user_id === userId || transaction.to_user_id === userId) {
        myTransactions++;
      }
    });
    
    this.setData({
      totalTransactions: this.data.transactions.length,
      totalIncome: totalIncome,
      myTransactions: myTransactions
    });
  },
  
  // 设置筛选条件
  setFilter: function(e) {
    const filter = e.currentTarget.dataset.filter;
    
    this.setData({ 
      activeFilter: filter,
      page: 1,
      hasMore: true,
      transactions: []
    });
    
    // 重新加载数据
    this.loadTransactions();
  },
  
  // 切换排序顺序
  sortTransactions: function() {
    const newSortOrder = this.data.sortOrder === 'desc' ? 'asc' : 'desc';
    
    this.setData({ 
      sortOrder: newSortOrder,
      page: 1,
      hasMore: true,
      transactions: []
    });
    
    // 重新加载数据
    this.loadTransactions();
  },
  
  // 加载更多
  loadMore: function() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadTransactions(true);
    }
  },
  
  // 格式化日期
  formatDate: function(dateString) {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    
    return `${year}-${month}-${day}`;
  },
  
  // 格式化时间
  formatTime: function(dateString) {
    const date = new Date(dateString);
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    
    return `${hours}:${minutes}`;
  },
  
  // 返回上一页
  navigateBack: function() {
    wx.navigateBack();
  },
  
  // 上拉触底加载更多
  onReachBottom: function() {
    this.loadMore();
  },
  
  // ---------------- 充值相关方法 ----------------
  
  // 选择充值金额
  selectAmount: function(e) {
    const amount = e.currentTarget.dataset.amount;
    this.setData({
      selectedAmount: amount,
      customAmount: ''
    });
  },
  
  // 输入自定义金额
  inputCustomAmount: function(e) {
    const amount = e.detail.value;
    this.setData({
      customAmount: amount,
      selectedAmount: 0
    });
  },
  
  // 确认充值
  confirmRecharge: function() {
    let amount = 0;
    
    if (this.data.selectedAmount > 0) {
      amount = this.data.selectedAmount;
    } else if (this.data.customAmount) {
      amount = parseInt(this.data.customAmount);
      if (isNaN(amount) || amount <= 0) {
        wx.showToast({
          title: '请输入有效金额',
          icon: 'none'
        });
        return;
      }
    } else {
      wx.showToast({
        title: '请选择充值金额',
        icon: 'none'
      });
      return;
    }
    
    wx.showLoading({ title: '处理中' });
    
    // 模拟充值
    setTimeout(() => {
      wx.hideLoading();
      
      wx.showModal({
        title: '充值成功',
        content: `成功充值 ${amount} 元`,
        showCancel: false,
        success: () => {
          // 更新余额（实际应从服务器获取）
          app.globalData.balance = (app.globalData.balance || 0) + amount;
          wx.navigateBack();
        }
      });
    }, 1000);
  },
  
  // ---------------- 转账相关方法 ----------------
  
  // 输入转账对象
  inputTransferTo: function(e) {
    this.setData({
      transferTo: e.detail.value
    });
  },
  
  // 输入转账金额
  inputTransferAmount: function(e) {
    this.setData({
      transferAmount: e.detail.value
    });
  },
  
  // 输入转账备注
  inputTransferRemark: function(e) {
    this.setData({
      transferRemark: e.detail.value
    });
  },
  
  // 确认转账
  confirmTransfer: function() {
    const { transferTo, transferAmount } = this.data;
    
    if (!transferTo.trim()) {
      wx.showToast({
        title: '请输入转账对象',
        icon: 'none'
      });
      return;
    }
    
    const amount = parseInt(transferAmount);
    if (isNaN(amount) || amount <= 0) {
      wx.showToast({
        title: '请输入有效金额',
        icon: 'none'
      });
      return;
    }
    
    // 检查余额（实际应从服务器验证）
    const currentBalance = app.globalData.balance || 0;
    if (amount > currentBalance) {
      wx.showToast({
        title: '余额不足',
        icon: 'none'
      });
      return;
    }
    
    wx.showLoading({ title: '处理中' });
    
    // 模拟转账
    setTimeout(() => {
      wx.hideLoading();
      
      wx.showModal({
        title: '转账成功',
        content: `成功向 ${transferTo} 转账 ${amount} 元`,
        showCancel: false,
        success: () => {
          // 更新余额（实际应从服务器获取）
          app.globalData.balance = currentBalance - amount;
          wx.navigateBack();
        }
      });
    }, 1000);
  },
  
  // 返回上一页
  goBack: function() {
    wx.navigateBack();
  }
});